package com.jblv.frame.config.util;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title ConfigXmlUtils
 * @projectName jblv-frame
 * @packageName com.jblv.frame.config.util
 * @description xml工具类
 * @date Create at 2020/9/7 15:36
 * @since jdk1.8
 */

import com.alibaba.fastjson.*;
import java.io.*;

import com.jblv.frame.config.bean.Config;
import org.springframework.core.io.*;
import org.dom4j.io.*;
import org.dom4j.*;
import java.util.*;
import org.slf4j.*;

public class ConfigXmlUtils
{
    private static Logger logger =  LoggerFactory.getLogger(ConfigXmlUtils.class);
    private static final String EMPTY_CONFIG = "\"\"";

    public static JSONObject load(final String path) throws Exception {
        InputStream in = null;
        try {
            final ResourceLoader resourceLoader = new DefaultResourceLoader();
            final Resource resource = resourceLoader.getResource(path);
            in = resource.getInputStream();
            final JSONObject json = new JSONObject(true);
            resolveConfigXml(in, json);
            return json;
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        finally {
            if (in != null) {
                in.close();
            }
        }
        return new JSONObject();
    }

    private static void resolveConfigXml(final InputStream in, final JSONObject json) throws DocumentException {
        final SAXReader saxReader = new SAXReader();
        final Document doc = saxReader.read(in);
        final List<Element> configItems = (List<Element>)doc.getRootElement().elements("config");
        for (int i = 0; i < configItems.size(); ++i) {
            final Element config = configItems.get(i);
            recursionForConfig(config, "", json);
        }
    }

    private static void recursionForConfig(final Element element, String name, final JSONObject json) {
        name = name + "." + element.attributeValue("name");
        final Iterator<Element> iterator = (Iterator<Element>)element.elementIterator("element");
        while (iterator.hasNext()) {
            recursionForConfig(iterator.next(), name, json);
        }
        String value = element.getTextTrim().trim();
        final String desc = element.attributeValue("desc");
        if (!"".equals(value)) {
            if ("\"\"".equals(value)) {
                value = "";
            }
            name = name.substring(1);
            final Config config = new Config();
            config.setName(name);
            config.setDesc(desc);
            config.setValue(value);
            config.setType(1);
            config.setAppId("");
            config.setAppNode("");
            json.put(name, (Object)config);
        }
    }

}